<!-- src/components/home/HomeBanner.vue -->
<script setup>
import { ref, onMounted, nextTick } from "vue";
import { useRouter } from 'vue-router';
import { getActiveBannersApi } from '../../api/banner';

const banners = ref([]);
const loading = ref(true);
const error = ref(null);
const swipeRef = ref(null);

const fetchBanners = async () => {
    try {
        console.log('开始获取轮播图...');
        const res = await getActiveBannersApi();
        console.log('获取成功:', res);

        if (res.data && Array.isArray(res.data)) {
            banners.value = res.data;

            // 使用 nextTick 确保 DOM 更新后再调整轮播图
            await nextTick();

            // 延迟执行 resize，确保组件完全渲染
            setTimeout(() => {
                if (swipeRef.value && swipeRef.value.resize) {
                    swipeRef.value.resize();
                }
            }, 700); // 增加延迟时间，确保渲染完成
        } else {
            throw new Error('返回数据格式错误');
        }
    } catch (error) {
        console.error('获取轮播图失败:', error);
        error.value = error.message || '获取轮播图失败';
    } finally {
        loading.value = false;
    }
};

onMounted(() => {
    fetchBanners();

    // 页面完全加载后再调整一次
    setTimeout(() => {
        if (swipeRef.value && swipeRef.value.resize) {
            swipeRef.value.resize();
        }
    }, 1000);
});

const router = useRouter();

function onClickSwipe(link) {
    // 如果有自定义链接，优先使用自定义链接
    if (link) {
        if (link.startsWith('/')) {
            router.push(link);
        } else {
            window.open(link);
        }
    } else {
        // 默认跳转到分类页面
        router.push('/category');
    }
}

function handleImageError(event) {
    event.target.src = 'https://via.placeholder.com/750x300/CCCCCC/999999?text=图片加载失败';
}
</script>

<template>
    <div class="home-banner">
        <!-- 骨架屏 -->
        <van-skeleton v-if="loading" :row="1" class="banner-skeleton" />

        <!-- 错误提示 -->
        <div v-else-if="error" class="error-message">
            {{ error }}
        </div>

        <!-- 轮播图 -->
        <van-swipe
            ref="swipeRef"
            v-else
            :autoplay="3000"
            :show-indicators="banners.length > 1"
            indicator-color="#ff6b35"
            class="banner-swipe"
            :loop="true"
            :touchable="true"
            :duration="500"
        >
            <van-swipe-item v-for="item in banners" :key="item.id" @click="onClickSwipe(item.link)">
                <div class="banner-item">
                    <img
                        class="banner-image"
                        :src="item.image_url"
                        :alt="item.title"
                        @error="handleImageError"
                    >
                    <div class="banner-overlay">
                        <div class="banner-title">{{ item.title }}</div>
                    </div>
                </div>
            </van-swipe-item>
        </van-swipe>
    </div>
</template>

<style lang="scss" scoped>
.home-banner {
  margin-bottom: 10px;
  position: relative;
  width: 100%;
}

.banner-skeleton {
  height: 180px;
  border-radius: 12px;
  overflow: hidden;
  margin: 0 16px;
}

.error-message {
    color: #f44336;
    padding: 16px;
    text-align: center;
    background-color: #fff5f5;
    border-radius: 8px;
    margin: 0 16px;
}

.banner-swipe {
  margin: 0 16px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  width: calc(100% - 32px);
  height: 180px;

  // 强制开启硬件加速
  transform: translateZ(0);
  -webkit-transform: translateZ(0);

  // 确保不会因为父容器影响而产生偏移
  position: relative;
  left: 0;
  top: 0;

  :deep(.van-swipe__indicators) {
    bottom: 12px;

    .van-swipe__indicator {
      width: 20px;
      height: 3px;
      border-radius: 3px;
      background-color: rgba(255, 255, 255, 0.5);

      &--active {
        background-color: #ff6b35;
      }
    }
  }

  :deep(.van-swipe__track) {
    transform: translateZ(0);
    -webkit-transform: translateZ(0);
  }

  :deep(.van-swipe-item) {
    // 确保每个轮播项不会溢出
    overflow: hidden;
    backface-visibility: hidden;
    -webkit-backface-visibility: hidden;
    cursor: pointer; // 添加手指光标提示可点击
  }
}

.banner-item {
  position: relative;
  height: 180px;
  overflow: hidden;
  width: 100%;
  flex-shrink: 0;

  // 添加硬件加速
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
}

.banner-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;

    // 防止图片加载时的闪烁
    image-rendering: -webkit-optimize-contrast;
}

.banner-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
  padding: 20px 16px 12px;
  color: white;

  // 防止文字模糊
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
}

.banner-title {
  font-size: 18px;
  font-weight: 600;
  line-height: 1.3;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}
</style>